<?php
/*
# ------------------------------------------------------------------------
# JA Teline III - Version 1.3 - Licence Owner jSharing.COM
# ------------------------------------------------------------------------
# Copyright (C) Lifetime Joomla Just for Sharing, Ltd. All Rights Reserved.
# @license - Copyrighted Commercial Software
# Author: Joomla Just for Sharing
# Websites:  http://jsharing.com -  http://jsharing.net
# This file may not be redistributed in whole or significant part.
# ------------------------------------------------------------------------
*/ 

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );



class plgContentPlg_JAComment extends JPlugin
{
	var $_plgCode = "#{jacomment(.*?)}#i";
	var $_plgCodeDisable = "#{jacomment(\s*)disable}#i";
	
	var $_url = "";
	var $_path = "";
	var $_postid = "";
	
	var $_comments = array();
	var $_commentsID = array();

	function plgContentPlg_JAComment( &$subject, $config )
	{
		parent::__construct( $subject, $config );

		$this->plugin = &JPluginHelper::getPlugin('content', 'plg_jacomment');
		$this->plgParams = new JParameter($this->plugin->params);
		$this->stylesheet ($this->plugin);
	}

	function onPrepareContent( &$article, &$params, $limitstart )
	{
		global $mainframe;
		global $option;
		
		$sectionid      = $article->sectionid;
		$catid          = $article->catid;
		$option 		= JRequest::getCmd('option');
		$view 			= JRequest::getCmd('view');
		$itemid 		= JRequest::getInt('Itemid');
		
		$check = true;
		if ($option != "com_content" || $view == "frontpage") 
			$check = false;
		
		if(!$article->id) {
			$check = false;
		}
		
		if(preg_match($this->_plgCodeDisable, $article->text)) {
			$check = false;
		}
		
		if (!$check) {
			$article->text = $this->removeCode($article->text);
			return;
		}
		
		$isComment = false;
		//
		$plugin = $this->plugin;
		$plgParams = $this->plgParams;

		//GET PLUGIN CONFIG
		$provider         = $plgParams->get('provider', 'intensedebate');
		switch($provider) 
		{
			case 'disqus': $provider = 'disqus'; break;
			case 'jskit': $provider = 'jskit'; break;
			case 'intensdebate': $provider = 'intensedebate'; break;
			default: $provider = 'intensedebate'; break;
		}
		$mode   		= $plgParams->get('mode','id');
		$catids         = $plgParams->get('catsid','');
		$tagmode        = $plgParams->get('tagmode',0);
		$display_comment_count  = $plgParams->get('display_comment_count',1);
		
		//
		$user 		    =& JFactory::getUser();
		$document       =& JFactory::getDocument();
		$this->document =& $document;
		
		//CHECK PAGE WAS SELECTED TO DISPLAY COMMENT FORM
		switch ($mode)
		{
			case 'disable':
				$article->text = $this->removeCode($article->text);
				return;
				break;
			case 'manual':
				if (!preg_match($this->_plgCode, $article->text)) {
					return;
				}
				break;
			case 'automatic':
			default:
				if (is_array($catids)){
					$categories = $catids;
				} elseif ($catids==''){
					$categories[] = $catid;
				} else {
					$categories[] = $catids;
				}
				
				if( !(in_array($catid,$categories) || preg_match($this->_plgCode, $article->text))) {
					return;
				}
				break;
		}
		//END OF CHECK
		$baseurl = $this->getUrlBase();
		
		if ($article->access <= $user->get('aid', 0)){
			$this->_path = JRoute::_(ContentHelperRoute::getArticleRoute($article->slug, $article->catslug, $article->sectionid));
		} else {
			$this->_path = JRoute::_("index.php?option=com_user&view=login");
		}
		$this->_url = $baseurl.$this->_path;
		if ($view=='article') 
			$isComment = true;
	
		$this->_postid = $article->id;
		
		if (!$isComment and $display_comment_count==0){ 
			return;
		}
		
		$this->isComment = $isComment;
		
		$output = $this->loadLayout ($this->plugin, $provider);
		
		/**
		 * JS Loading Optimize
		 * create place holder for comment 
		 */
		$container = 'JaCommentContainer'.$article->id;
		$holder = 'JaCommentPlaceHolder'.$article->id;
		
		$store = &Plg_comment_storage::getInstance();
		$store->_comments[] = '<div id="'.$container.'">'.$output.'</div>';
		$store->_commentsID[] = $article->id;
		
		$output = '<div id="'.$holder.'"></div>';
		
		if ($mode == 'manual' || preg_match($this->_plgCode, $article->text)) {
			$article->text = preg_replace( $this->_plgCode, $output, $article->text );
		} else {
			$article->text .= $output;
		}
		
	
		return true;
		
	}

	function onAfterRender(){
		$store = &Plg_comment_storage::getInstance();
		
		$this->_comments = $store->_comments;
		$this->_commentsID = $store->_commentsID;
		
		$body = JResponse::getBody();
		$comments = $this->loadLayout($this->plugin, 'common');
		$body = str_replace('</body>', $comments."\n</body>",$body);
		JResponse::setBody($body);
	}
	
	function removeCode($content)
	{
		return preg_replace( $this->_plgCode, '', $content );
	}
	
	function getUrlBase()
	{
		$baseurl = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['HTTP_HOST'] : "http://".$_SERVER['HTTP_HOST'];
		if ($_SERVER['SERVER_PORT']!="80") 
			$baseurl .= ":".$_SERVER['SERVER_PORT'];
		
		return $baseurl;
	}
	
	function getLayoutPath($plugin, $layout = 'default')
	{
		global $mainframe;

		// Build the template and base path for the layout
		$tPath = JPATH_BASE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.$plugin->name.DS.$layout.'.php';
		$bPath = JPATH_BASE.DS.'plugins'.DS.$plugin->type.DS.$plugin->name.DS.'tmpl'.DS.$layout.'.php';
		// If the template has a layout override use it
		if (file_exists($tPath)) {
			return $tPath;
		} elseif (file_exists($bPath)) {
			return $bPath;
		}
		return '';
	}

	function loadLayout ($plugin, $layout = 'default') {
		$layout_path = $this->getLayoutPath ($plugin, $layout);
		if ($layout_path) {
			ob_start();
			require $layout_path;
			$content = ob_get_contents();
			ob_end_clean();
			return $content;
		}
		return '';
	}

	function stylesheet ($plugin) {
		global $mainframe;
		JHTML::stylesheet('style.css','plugins/'.$plugin->type.'/'.$plugin->name.'/');
		if (is_file(JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'css'.DS.$plugin->name.".css"))
		JHTML::stylesheet($plugin->name.".css",'templates/'.$mainframe->getTemplate().'/css/');
	} 
}

class Plg_comment_storage {
	var $_comments = array();
	var $_commentsID = array();
	
	function &getInstance () {
		static $instance = null;
		
		if ($instance == null){ 
			$instance = new Plg_comment_storage();
		}
		
		return $instance;
	}
}


function JA_MakeSefUrl($url)
{
	$regex  = '#index.php\?([^"]*)#m';
	$sefURL = preg_replace_callback( $regex, "JA_ConvertUrl", $url );
	return $sefURL;
}
/**
 * convert from normal format to sef format
 *
 * @param unknown_type $matches
 * @return unknown
 */
function JA_ConvertUrl(&$matches)
{
	$original       = $matches[0];
	$url            = $matches[1];
	
	if(strpos($original, 'index.php/') !== false) {
		return $original;
	}
	/**
	 * 
	 */
	$url = str_replace('&amp;','&',$url);
	$aTemp = explode('&', $url);
	
	$aParams = array();
	foreach ($aTemp as $param) {
		list($key, $value) = split('=', $param, 2);
		$aParams[$key] = $value;
	}
	
	$sefUrl = "";
	list($catid, $cat) = split(':', $aParams['catid'], 2);
	list($id, $article) = split(':', $aParams['id'], 2);
	/**
	 * 
	 */
	$db = &JFactory::getDBO();
	
	$query = "
		SELECT 
			s.alias AS section,
			cat.alias AS category,
			c.id,
			c.catid,
			c.sectionid,
			c.alias AS title
		FROM #__content c
		INNER JOIN #__categories cat ON cat.id = c.catid
		INNER JOIN #__sections s ON s.id = c.sectionid
		WHERE c.id = " . (int) $id;
	$db->setQuery($query);
	$row = $db->loadAssoc();
	if($row == null) {
		return $original;
	}
	
	//create sef url
	$pos = (int) strpos($original, 'index.php?');
	$sefUrl = substr($original, 0, $pos);
	$sefUrl .= "index.php/" . $row['section'] . "/" . $row['category'] . "/" . $row['id'] . "-" . $row['title'];
	return  $sefUrl;
	
	
}
?>